package com.gqr.springcloud;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.UUID;

@RestController
public class Controller {

    @Resource
    private JwtService jwtService;

    @Resource
    private RedisTemplate redisTemplate;
    @PostMapping("/login")
    public AuthResponse login(@RequestParam String username,
                              @RequestParam String password
                              ){
        Account account = Account.builder()
                .username(username)
                .build();

        // TODO 验证username + password
        String token = jwtService.token(account);
        account.setToken(token);
        account.setRefreshToken(UUID.randomUUID().toString());

        redisTemplate.opsForValue().set(account.getRefreshToken(),account);
        return AuthResponse.builder()
                .account(account)
                .code(AuthResponseCode.SUCCESS)
                .build();
    }

    @PostMapping("/refresh")
    @ResponseBody
    public AuthResponse refresh(@RequestParam String refreshToken){
       Account account = (Account) redisTemplate.opsForValue().get(refreshToken);
        if(account==null){
            return AuthResponse.builder().code(AuthResponseCode.USER_NOT_FOUND).build();
        }
        String jwt = jwtService.token(account);
        account.setToken(jwt);
        account.setRefreshToken(UUID.randomUUID().toString());
        redisTemplate.delete(refreshToken);

        redisTemplate.opsForValue().set(account.getRefreshToken(),account);
        return AuthResponse.builder()
                .account(account)
                .code(AuthResponseCode.SUCCESS)
                .build();
    }

    @GetMapping("/verify")
    @ResponseBody
    public AuthResponse verify(
            @RequestParam String token,
            @RequestParam String username
            ){
        boolean success = jwtService.verify(token, username);
        return AuthResponse.builder()
                // TODO 此处最好用invalid token之类的错误信息
                .code(success?AuthResponseCode.SUCCESS:AuthResponseCode.USER_NOT_FOUND)
                .build();
    }


}
